<template>
    <div>
        <el-dialog :destroy-on-close="true"
                   :title="isAddPage?'添加权限':'修改权限'"
                   :close-on-click-modal="false"
                   @close="closeDialog"
                   :visible="visible"
                   width="1100px">
    <div>
        <el-row >
            <el-col :span="8"  >
                <el-form ref="formRef" :model="form" :rules="rules"  label-width="100px" >
                    <el-form-item label="权限名称"  prop="authName">
                        <el-input  v-model="form.authName"></el-input>
                    </el-form-item>
                    <el-form-item label="类型"  prop="authType">
                        <el-select v-model="form.authType" filterable  clearable class="w100"   >
                            <el-option
                                    v-for="item in this.$constant.authTypeEnum"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否启用"  prop="isEnable">
                        <el-checkbox v-model="form.isEnable"></el-checkbox>
                    </el-form-item>

                </el-form>
            </el-col>

            <el-col :span="16" style="padding: 0px 0px 0px 10px"  >
                <el-table
                        border stripe  header-cell-class-name="t_h_cell" class="data-table"
                        :data="form.menuList" row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                        :v-loading="loading"     default-expand-all
                        :height=dataTableHeight ref="tableRef"
                        @select="selectFun"
                        @select-all="selectAllFun"
                    >
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>

                    <el-table-column  :width="220" :show-overflow-tooltip="true"
                                      prop="menuName" label="菜单名称">
                    </el-table-column>

                    <el-table-column prop="id" label="操作权限">
                        <template  slot-scope="scope">
                            <el-checkbox v-model="optItem.checked"   v-for="(optItem) in scope.row.operations">{{optItem.optName}} </el-checkbox>
                        </template>
                    </el-table-column>

                </el-table>
            </el-col>

        </el-row>

        <el-row style="text-align: right; ">
                <el-button type="primary" @click="submitForm()">保存</el-button>
                <el-button @click="closeDialog" >取消</el-button>
        </el-row>

    </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        components: {
        },
        props: ['visible'],
        data() {
            return {
                isAddPage:true,

                form: {
                    isEnable:true,
                    menuList:[
                    ],
                },
                rules: {
                    authName: [
                        { required: true, message: '请输入数据', trigger: 'blur' },
                        { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }
                    ],
                    authType: [
                        { required: true, message: '请输入数据', trigger: 'blur' },
                    ],
                },
                dataTableHeight:370,
                loading:false,

            }
        },
        created() {


        },
        mounted() {
            //console.log("form",this.form);
            /*this.form.menuList.forEach((item) => {
                item.checked = false; //默认为不选中
                if (item.children && item.children.length) {
                    this.initData(item.children);
                }
            });*/
        },
        methods: {
            indexData(index){
                return index+1;
            },
            selectFun(selection, row) {
                this.setRowChecked(row);
            },
            setRowChecked(row) {
                //当点击父级点复选框时，当前的状态可能为未知状态，所以当前行状态设为false并选中，即可实现子级点全选效果
                if (row.checked === "") {
                    //row.checked = false;
                    row.checked = true;
                    this.$refs.tableRef.toggleRowSelection(row, true);
                }
                row.checked = !row.checked;
                let that = this;

                function selectAllChildren(data) {
                    data.forEach((item) => {
                        item.checked = row.checked;
                        that.$refs.tableRef.toggleRowSelection(item, row.checked);
                        if (item.children && item.children.length) {
                            selectAllChildren(item.children);
                        }
                    });
                }

                function getSelectStatus(selectStatusArr, data) {
                    if (data===undefined){
                        return  selectStatusArr;
                    }
                    data.forEach((childrenItem) => {
                        selectStatusArr.push(childrenItem.checked);
                        if (childrenItem.children && childrenItem.children.length) {
                            getSelectStatus(selectStatusArr, childrenItem.children);
                        }
                    });
                    return selectStatusArr;
                }
                function getLevelStatus(row) {
                    //如果当前节点的parantId =0 并且有子节点，则为1
                    //如果当前节点的parantId !=0 并且子节点没有子节点 则为3
                    if (row.pid === 0) {
                        if (row.children && row.children.length) {
                            return 1;
                        }else{
                            return 4;
                        }
                    } else {
                        if (!row.children || !row.children.length) {
                            return 3;
                        } else {
                            return 2;
                        }
                    }
                }
                let result = {};
                //获取明确的节点
                function getExplicitNode(data,pid) {
                    data.forEach((item) => {
                        if(item.id === pid) {
                            result = item;
                        }
                        if(item.children && item.children.length) {
                            getExplicitNode(item.children,pid);
                        }
                    })
                    return result;
                }
                function operateLastLeve(row) {
                    //操作的是子节点  1、获取父节点  2、判断子节点选中个数，如果全部选中则父节点设为选中状态，如果都不选中，则为不选中状态，如果部分选择，则设为不明确状态
                    let selectStatusArr = [];
                    let item = getExplicitNode(that.form.menuList,row.pid);
                    selectStatusArr = getSelectStatus(selectStatusArr, item.children);
                    if (selectStatusArr.every((selectItem) => {
                            return true === selectItem;
                        })) {
                        item.checked = true;
                        that.$refs.tableRef.toggleRowSelection(item, true);
                    } else if (
                        selectStatusArr.every((selectItem) => {
                            return false === selectItem;
                        })) {
                        //item.checked = false;
                        //that.$refs.tableRef.toggleRowSelection(item, false);
                    } else {
                        item.checked = "";
                    }
                    //则还有父级
                    if(item.pid!==0) {
                        operateLastLeve(item)
                    }
                }
                //判断操作的是子级点复选框还是父级点复选框，如果是父级点，则控制子级点的全选和不全选

                //1、只是父级 2、既是子集，又是父级 3、只是子级
                let levelStatus = getLevelStatus(row);
                if (levelStatus === 1) {
                    selectAllChildren(row.children);
                } else if (levelStatus === 2) {
                    selectAllChildren(row.children);
                    operateLastLeve(row);
                } else if(levelStatus === 3) {
                    operateLastLeve(row);
                }
            },
            selectAllFun(selection) {
                let isAllSelect = this.checkIsAllSelect();
                this.form.menuList.forEach((item) => {
                    item.checked = isAllSelect;
                    this.$refs.tableRef.toggleRowSelection(item, !isAllSelect);
                    this.selectFun(selection, item);
                });
            },
            /*rowClassNameFun({ row }) {
                if (row.checked === "") {
                    return "indeterminate";
                }
            },
            headerRowClassName({ row }) {
                let oneProductchecked = [];
                this.form.menuList.forEach((item) => {
                    oneProductchecked.push(item.checked);
                });
                if (oneProductchecked.includes("")) {
                    return "indeterminate";
                }
                return "";
            },*/
            checkIsAllSelect() {
                this.oneProductchecked = [];
                this.form.menuList.forEach((item) => {
                    this.oneProductchecked.push(item.checked);
                });
                //判断一级产品是否是全选.如果一级产品全为true，则设置为取消全选，否则全选
                return this.oneProductchecked.every((selectStatusItem) => {
                    return true === selectStatusItem;
                });
            },


           /* async loadMenuData(groupID){
                let _this=this;
                let url='/auth/getAuthMenu/'+groupID;
                _this.loading=true;
                await _this.$http.post(url,_this.query).then(function(res){
                    if(res.data.success){
                        _this.form.menuList=res.data.data;
                    }else{
                        _this.$message.error('获取数据错误！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
                    }
                },function(){
                    _this.$message.error('获取数据错误！');
                });
                _this.loading=false;
            },*/

            closeDialog() {
                this.$emit('update:visible',false);
                //Object.assign(this.$data, this.$options.data());
            },
            submitForm(){
                let _this=this;
                let url='/auth/save';
                if (!_this.isAddPage){
                    url='/auth/update';
                }
                this.$utils.submitFormData(_this,_this.$refs.formRef,url,_this.form,function (valid) {
                    //TODO 权限不能空
                    console.log(_this.form.menuList);
                    if (!_this.isHasChecked(_this.form.menuList)){
                        _this.$message.error("请选择菜单权限");
                        valid=false;
                    }
                    return valid;
                },function () {
                    _this.closeDialog();
                    _this.$emit('loadData', true);
                });
            },

            isHasChecked(rows){
                //console.log(rows);
                let result=false;
                for (let row of rows) {
                    if (row.checked) {
                        result=true;
                    }else if (row.children  && row.children.length>0){
                        let cp=this.isHasChecked(row.children);
                        if (cp){
                            result=true;
                        }
                    }
                }
                return result;
            },

            initData(){
                this.isAddPage=true;
                this.form={
                    isEnable:true,
                    menuList: [],
                }

                let _this=this;
                setTimeout(function(){
                    _this.$http.post('/auth/getAuthMenuListForCheck').then(function(res){
                        if(res.data.success){
                            _this.form.menuList=res.data.data;
                            //_this.loadMenuData(_this.form.id);
                        }else{
                            _this.$message.error('操作失败！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
                        }
                    },function(){
                        _this.$message.error('操作失败！');
                    });
                }, 100);


            },
            async loadData(row){
                let _this=this;
                this.isAddPage=false;
                //setTimeout(function(){
                await  _this.$http.post('/auth/getAuth/'+row.id).then(function(res){
                        if(res.data.success){
                            _this.form=res.data.data;
                           /* setTimeout(function(){
                                _this.setChecked(_this.form.menuList);
                            }, 200);*/
                            _this.$nextTick(function () {
                                _this.setChecked(_this.form.menuList);
                            });
                        }else{
                            _this.$message.error('操作失败！错误编码:'+res.data.code+'错误原因:'+res.data.msg);
                        }
                    },function(){
                        _this.$message.error('操作失败！');
                    });
                //}, 100);
            },

            setChecked(rows){
                let _this=this;
                for (let i = 0; i <rows.length; i++) {
                    let row=rows[i];
                    if (row.checked){
                        _this.$refs.tableRef.toggleRowSelection(row, true);
                    }
                    if (row.children && row.children.length>0){
                       this.setChecked(row.children);
                    }
                }
            },


        },

        filters: {

        },
        watch:{

        }
    }

</script>
